// 问卷调查
import React, { useReducer, useState } from "react";
import { store } from "../../store/index";
import queryApi from "../../api/query";

const SpeedContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "get_speed":
      return action.payload.quesSpeed;
    default:
      return state;
  }
};

let initData = [];

export const SpeedProvider = ({ children }) => {
  const [SpeedData, dispatch] = useReducer(dataReducer, initData);
  const [dateArr, setDateArr] = useState([]);
  const [tDateArr, setTDateArr] = useState([]);

  const getSpeed = async () => {
    try {
      let user = store.getState().authR.user;
      let data;
      if (user.role == "admin") {
        data = await queryApi.get("quesspeed/group", {
          params: { group: user.group },
        });
      } else {
        data = await queryApi.get("quesspeed/group", {
          params: { group: "-1" },
        });
      }
      console.log("查找调研进度成功---", data.data.status);
      let speeds = data.data.data;
      let t_dateArr = [];
      let t_tDateArr = [];
      for (let i = 0; i < speeds.length; i++) {
        // console.log("时间---", speeds[i].time);
        let date1 = new Date(speeds[i].time);
        date1 =
          date1.getFullYear() +
          "-" +
          (date1.getMonth() + 1) +
          "-" +
          date1.getDate();
        let date2 = new Date(speeds[i].time).setHours(0, 0, 0, 0);
        if (t_tDateArr.indexOf(date2) == -1) {
          // console.log("时间啊---", date1, "---", date2);
          t_tDateArr.push(date2);
          t_dateArr.push(date1);
        }
      }
      t_dateArr.push("全部");
      t_tDateArr.push("全部");
      setDateArr([...t_dateArr]);
      setTDateArr([...t_tDateArr]);
      dispatch({ type: "get_speed", payload: { quesSpeed: speeds } });
    } catch (error) {
      console.log("查找调研进度失败---", error);
    }
  };

  return (
    <SpeedContext.Provider value={{ SpeedData, getSpeed, tDateArr, dateArr }}>
      {children}
    </SpeedContext.Provider>
  );
};

export default SpeedContext;
